<style>
    #add-battery-content{
        margin-top:20px;
    }
    .form-tips{
        font-size:0.7em;
    }
    .soft-alert{
        color:#03a9f4;
        display: block;
    }
    .state-init{
        display:none;
    }
    .state-error{
        display: block;
        color:red;
    }
    div.user-details{
        display: none;
    }
    .for-new-btry{
        display:none;
    }
    .for-old-btry{
        display:none;
    }
    #user-info-tips{
        display:none;
        font-size: 0.7em;
        color: white;
        background: #03a9f4;
        border-radius: 10px;
        text-align: center;
    }
</style>

<div id="add-battery-content" class="container">

    <div class="row">

        <div class="center-block col-sm-8">

            <div class="card">
                <div class="card-header">
                    <i class="fa fa-plus fa-lg"></i>
                    <strong> باتارىيە قوشۇش </strong>
                    <div class="card-actions">
                        <a href="#" class="btn-close"><i class="icon-close"></i></a>
                    </div>
                </div>
                <div class="card-block">
                    <form role="form" class="add-battery-form">

                        <div class="form-group">
                            <label> تىلفۇن نۇمۇرى </label>
                            <input id="userPhone" type="number" class="form-control" onblur="checkExists(this)" onchange="goValidate(this);" name="userPhone" placeholder="11 خانە رەقەم كىرگۈزۈڭ ">
                            <span class="form-tips state-init">ئىناۋەتلىك تېلفۇن نۇمۇرى كىرگۈزۈۈڭ</span>
                        </div>


                        <!-- user information start-->
                        <p id="user-info-tips">بۇ نۇمۇرنىڭ ئۇچۇرى تىپىلمىدى! تۆۋەندىكى ئۇچۇرلارنى تولۇقلاڭ.</p>
                        <div class="form-group user-details">
                            <label> خىرىدار ئىسمى </label>
                            <input id="uName" type="text" class="form-control" onkeyup="goValidate(this)" name="uName">
                            <span class="form-tips state-init">ئىناۋەتلىك نام كىرگۈزۈڭ</span>
                        </div>
                        <!-- Location -->
                        <div class="form-group col-sm-6 user-details">
                            <label> ۋىلايەت </label>
                            <select name="sel-cities" class="form-control" onchange="selCiChanged(this);" size="1">
                                <option value="">--- تاللاڭ ---</option>
                            </select>
                            <span class="form-tips state-init"> ۋىلايەتنى تاللاڭ</span>
                        </div>
                        <div class="form-group col-sm-6 user-details">
                            <label> ناھىيە </label>
                            <select id="uDistricts" name="sel-districts" class="form-control" onclick="goValidate(this);" size="1">

                            </select>
                            <span class="form-tips state-init">ناھىيەنى جەزىملەشتۈرۈڭ</span>
                        </div>
                        <div class="form-group user-details">
                            <label> رايون / يىزا-بازار </label>
                            <input type="text" class="form-control" name="mVillage" placeholder="">
                        </div>
                        <!-- user information end-->

                        <hr style="border: #03A9F4 1px double;">

                        <!-- battery info-->
                        <div class="form-group btry-basic-info">
                            <label> باتارىيە تىپى </label>
                            <select name="batteryType" class="form-control" size="1" onclick="goValidate(this)">
                                <option value="">--- تاللاڭ ---</option>
                                <option value="1"> 1 </option>
                                <option value="2"> 2 </option>
                                <option value="3"> 3 </option>
                                <option value="4"> 4 </option>
                            </select>
                            <span class="form-tips state-init">باتارىيە تىپىنى تاللاڭ</span>
                        </div>

                        <div class="form-group  btry-basic-info">
                            <label> تەرتىپ نۇمۇرى </label>
                            <input type="text" class="form-control" onkeyup="goValidate(this)" name="batterySeriesNumber">
                            <span class="form-tips state-init">ئىناۋەتلىك تەرتىپ نۇمۇرى كىرگۈزۈڭ</span>
                        </div>

                        <div class="form-group  btry-basic-info">
                            <label> زاۋۇتى </label>
                            <select name="factoryName" class="form-control" size="1" onclick="goValidate(this)">
                                <option value="">--- تاللاڭ ---</option>
                                <option value="g1"> 1-ئەۋلاد </option>
                                <option value="g2"> 2-ئەۋلاد </option>
                            </select>
                            <span class="form-tips state-init">زاۋۇتنى تاللاڭ</span>
                        </div>

                        <div class="form-group col-sm-6  btry-basic-info">
                            <label> مەسىلە تۈرى </label>
                            <select name="damageType" class="form-control" size="1" onclick="goValidate(this)">
                                <option value="">--- تاللاڭ ---</option>
                                <option value="1"> كىسلاتا تۈگىگەن </option>
                                <option value="2"> ئىششىپ قالغان </option>
                            </select>
                            <span class="form-tips state-init">مەسىلە تۈرىنى تاللاڭ</span>
                        </div>

                        <div class="form-group col-sm-6  btry-basic-info">
                            <label> نەتىجىسى </label>
                            <select name="result" class="form-control" size="1" onclick="goValidate(this)">
                                <option value="">--- تاللاڭ ---</option>
                                <option value="1"> ئوڭشالدى </option>
                                <option value="2"> ئۆلدى </option>
                            </select>
                            <span class="form-tips state-init">نەتىجىسىنى تاللاڭ</span>
                        </div>


                        <div class="form-group row">
                            <label class="col-md-4 form-control-label"> يىڭىمۇ؟ </label>
                            <div class="col-md-8" onclick="radioClicked(this)">
                                <label class="radio-inline" for="isNewY">
                                    <input type="radio" id="isNewY" name="isNew" value="true"> يىڭى
                                </label>
                                <label class="radio-inline" for="isNewN">
                                    <input type="radio" id="isNewN" name="isNew" value="false"> كونا
                                </label>
                            </div>
                            <span class="form-tips state-error" style="margin: 0 2em;"> بىرنى تاللاڭ </span>
                        </div>

                        <!-- isNew true -->
                        <div class="form-group for-new-btry">
                            <label> زاۋۇت ۋاقتى </label>
                            <input data-toggle="datepicker" id="factoryTime" class="form-control" name="factoryTime" onclick="">
                            <span class="form-tips soft-alert">زاۋۇت ۋاقىتىنى تاللاڭ</span>
                        </div>
                        <div class="form-group for-new-btry">
                            <label> سېتىلغان ۋاقتى </label>
                            <input data-toggle="datepicker" id="saleTime" class="form-control" name="saleTime" onclick="">
                            <span class="form-tips soft-alert">سېتىلغان ۋاقىتىنى تاللاڭ</span>
                        </div>

                        <!-- isNew false -->
                        <div class="form-group row for-old-btry isNewNo">
                            <label class="col-md-3 form-control-label"> باشقىلار </label>
                            <div class="col-md-9">
                                <label class="checkbox-inline" for="isChanged">
                                    <input type="checkbox" id="isChanged" name="isChanged" value="true"> ئۆزگەرتكەنمۇ؟
                                </label>
                                <label class="checkbox-inline" for="isReplaced">
                                    <input type="checkbox" id="isReplaced" name="isReplaced" value="true"> ئالماشتۇرغانمۇ؟
                                </label>
                                <label class="checkbox-inline" for="isResaled">
                                    <input type="checkbox" id="isResaled" name="isResaled" value="true"> قايتا سېتىلغانمۇ؟
                                </label>
                            </div>
                        </div>

                        <div class="form-group for-old-btry isChanged">
                            <label> ئۆزگەرتكەن ۋاقتى </label>
                            <input data-toggle="datepicker" class="form-control" id="changedTime" name="changedTime">
                            <span class="form-tips soft-alert">ئۆزگەرتكەن ۋاقىتىنى تاللاڭ</span>
                        </div>
                        <div class="form-group for-old-btry isReplaced">
                            <label> ئالماشتۇرغان ۋاقتى </label>
                            <input data-toggle="datepicker" class="form-control" id="replacedTime" name="replacedTime">
                            <span class="form-tips soft-alert">ئالماشتۇرغان ۋاقىتىنى تاللاڭ</span>
                        </div>
                        <div class="form-group for-old-btry isResaled">
                            <label> قايتا سېتىلغان ۋاقتى </label>
                            <input data-toggle="datepicker" class="form-control" id="resaledTime" name="resaledTime">
                            <span class="form-tips soft-alert">قايتا سېتىلغان ۋاقىتىنى تاللاڭ</span>
                        </div>

                    </form>
                </div>
                <div class="card-footer">
                    <button type="submit" href="#" onclick="addBtry()" class="btn btn-primary"><i class="fa fa-check-square-o"></i> تاپشۇرۇش </button>
                    <button type="reset" class="btn btn-danger" onclick="resetClicked()"><i class="fa fa-ban"></i> ئەسلىگە قايتۇرۇش </button>
                </div>
            </div>
        </div>
    </div>

</div>

<script>

    $(document).ready(function () {

        loadCities();

    });

    function loadCities() {
        var selectorCi = $("select[name='sel-cities']");
        net.get('region/cities',null,function (error) {

        },function (response) {
            $.each(response.data,function (index,value) {
                $(selectorCi).append("<option value='"+value.id+"'>"+value.ugName+"   "+value.chName+"</option>");
            });
        });
    }

    function selCiChanged(selector) {
        var cityId = $(selector).val();
        var selectorDi = $("select[name='sel-districts']");
        //清空次级菜单
        $(selectorDi).empty();

        if(cityId == ''){
            //
            $(selector).next().removeClass('state-init').addClass('state-error')
        }else{
            $(selector).next().removeClass('state-error').addClass('state-init');

            net.get('region/districts',{'cityId':cityId},function (error) {

            },function (response) {
                $.each(response.data,function (index,value) {
                    $(selectorDi).append("<option value='"+value.id+"'>"+value.ugName+"   "+value.chName+"</option>");
                });
                //第一次提示改变次级菜单
                $(selectorDi).next().removeClass('state-init').addClass('state-error');
            });
        }

    }

    // 三个checkbox
    $("div.isNewNo input").on('click',function () {
        if($('#isChanged').prop('checked')){
            $("div.isChanged").show();
        }else{
            $("div.isChanged").hide();
        }
        if($('#isReplaced').prop('checked')){
            $("div.isReplaced").show();
        }else{
            $("div.isReplaced").hide();
        }
        if($('#isResaled').prop('checked')){
            $("div.isResaled").show();
        }else{
            $("div.isResaled").hide();
        }

    });

    //初始化所有datepicker
    $('[data-toggle="datepicker"]').datepicker({
        autoHide: true,
        zIndex: 2048,
        language : 'ug-CN'
    });

    /**
     * check user existence by phone number
     * @param input
     */
    function checkExists(input) {
        if(!$(input).next().hasClass('state-error')){
            //查询
            net.get("battery/isExist",{'userPhone':$(input).val()},function (error) {

            },function (response) {
                console.log('isExist:',response.data);
                if(response.data == false){
                    $("#user-info-tips").show();
                    $("div.user-details").show();
                }else{
                    $("#user-info-tips").hide();
                    $("div.user-details").hide();
                }
            });

        }

    }

    function radioClicked(x) {
        var isNew = $("input[name='isNew']:checked").val();
        if(!isNew){
            $(x).next().removeClass('state-init').addClass('state-error');
        }else if(isNew == 'true'){
            $(x).next().removeClass('state-error').addClass('state-init');
            $("div.for-old-btry").hide();
            $("div.for-old-btry input").val('');
            $("div.for-new-btry").show();
        }else if(isNew == 'false'){
            $(x).next().removeClass('state-error').addClass('state-init');
            $("div.for-new-btry").hide();
            $(".isNewNo input[type=checkbox]").prop('checked',false);
            $("div.for-new-btry input").val('');
            $("div.isNewNo").show();
        }
    }

    function dynamicValidate() {
        var isNew = $("input[name='isNew']:checked").val();
        if(!isNew){
            return false;
        }else if(isNew == 'true'){
            if(!$("#factoryTime").val() || !$("#saleTime").val()){ return false; }
        }else if(isNew == 'false'){
            if(!$("#isReplaced").prop('checked') && !$("#isResaled").prop('checked') && !$("#isChanged").prop('checked')){
                return false;
            }
            if($("#isChanged").prop('checked')){
                if(!$("#changedTime").val()) return false;
            }
            if($("#isReplaced").prop('checked')){
                if(!$("#replacedTime").val()) return false;
            }
            if($("#isResaled").prop('checked')){
                if(!$("#resaledTime").val()) return false;
            }
        }
        return true;
    }

    function hasStateErr() {
        var isThere = false;
        $(".add-battery-form .form-tips").each(function () {
            if($(this).hasClass("state-error")){
                console.log("state-error location:",$(this)[0].previousElementSibling.tagName,$(this)[0].previousElementSibling.name);
                isThere = true;
                return true;
            }
        });
        return isThere;
    }
    
    function hasNull() {
        // user info
        if(!$("#userPhone").val()){
            $("#userPhone").next().removeClass('state-init').addClass('state-error');
        }else if($("#user-info-tips").css("display") != "none"){
            if(!$("#uName").val()){
                $("#uName").next().removeClass('state-init').addClass('state-error');
            }
            if(!$("#uDistricts").val()){
                $("#uDistricts").next().removeClass('state-init').addClass('state-error');
            }
        }
        // battery basic info
        $("div.btry-basic-info input").each(function () {
            if($(this).val() == "" || $(this).val() == "undefined"){
                console.log("null value location:",$(this)[0].name);
                var input_name = $(this)[0].name;
                $("input[name='"+input_name+"']").next().removeClass("state-init").addClass("state-error");
                return;
            }
        });
        $("div.btry-basic-info select").each(function () {
            if($(this).val() == "" || $(this).val() == "undefined"){
                console.log("null value location:",$(this)[0].name);
                var select_name = $(this)[0].name;
                $("select[name='"+select_name+"']").next().removeClass("state-init").addClass("state-error");
                return false;
            }
        });

    }

    function addBtry() {

        if(!dynamicValidate()){
            dia.alert('تەكشۈرۈڭ','جەدۋەل توشقۇزىشىڭىز تولۇق بولمىدى !بەكرەك تەكشۈرۈپ بىقىڭ! ',['بىلدىم'],'fa fa-times-circle-o',function () {

            });
            return;
        }
        //判断是否有还没填的项
        hasNull();
        
        if(hasStateErr()){
            dia.alert('تەكشۈرۈڭ','جەدۋەل توشقۇزىشىڭىز توغرا بولمىدى ! قىزىل رەڭلىك ئەسكەرتىشكە دىققەت قىلىڭ! ',['بىلدىم'],'fa fa-times-circle-o',function () {

            });
            return ;
        }
        
        var serializeArr = $(".add-battery-form").serializeArray();
        var Obj = arr2Json(serializeArr);
        console.log("---------debug----",Obj);

        net.post("battery/add",Obj,function (error) {

        },function (response) {
            dia.alert('ئەسكەرتىش','بىر باتارىيە قوشۇلدى!',['بىلدىم'],'fa fa-check',function (btn_name) {
                resetClicked();
            });
        });
    }


    function arr2Json(arr){
        var obj = {};
        $(arr).each(function(){
            obj[this.name]=this.value;
        });
        console.log("--obj--",obj);

        var encapsulated =
            {
                "batteryUser": {
                    "userName": obj['uName'],
                    "userPhone": obj['userPhone'],
                    "userVillage": obj['mVillage'],
                    "district": {
                        "id": obj['sel-districts'],
                        "city": {
                            "id": obj['sel-cities']
                        }
                    }
                },
                "batteryType": obj['batteryType'],
                "batterySeriesNumber": obj['batterySeriesNumber'],
                "factoryName": obj['factoryName'],
                "factoryTime": date2stamp(obj['factoryTime']),
                "saleTime": date2stamp(obj['saleTime']),
                "replaceTime": date2stamp(obj['replacedTime']),
                "changeTime": date2stamp(obj['changedTime']),
                "resaleTime": date2stamp(obj['resaledTime']),
                "damageType": obj['damageType'],
                "result": obj['result'],
                "new": obj['isNew']=='true',
                "changed": obj['isChanged']=='',
                "replaced": obj['isReplaced']=='',
                "resaled": obj['isResaled']==''
            };

        return encapsulated;
    }

    function resetClicked() {
        $("#vav-add-battery").click();
        return;
    }

    function date2stamp(dateStr) {
        if(dateStr){
            return Date.parse(dateStr.trim());
        }else{
            return null;
        }
    }

    function goValidate(x) {

        if(x.name == 'userPhone'){
            //手机号验证正则
            var telReg = RegExp(/^1[234578]\d{9}$/);

            if (!telReg.test(x.value)) {
                $(x).next().removeClass('state-init').addClass('state-error');
            }else{
                $(x).next().removeClass('state-error').addClass('state-init');
            }
            return;
        }

        //特殊字符正则
        var containSpecial = RegExp(/[(\~)(\!)(\@)(\#)(\$)(\%)(\^)(\&)(\*)(\()(\))(\-)(\_)(\+)(\=)(\[)(\])(\{)(\})(\|)(\\)(\;)(\:)(\')(\")(\,)(\.)(\/)(\<)(\>)(\?)(\)]+/);

        //mName验证
        if(x.name == "uName") {
            if (containSpecial.test(x.value)) {
                $(x).next().removeClass('state-init').addClass('state-error');
            }else{
                $(x).next().removeClass('state-error').addClass('state-init');
            }
            return;
        }

        if(x.name == "sel-districts") {
            //判断父级菜单
            var selectorCi = $("select[name='sel-cities']");
            if(selectorCi.val() == ''){
                selectorCi.next().removeClass('state-init').addClass('state-error');
            }else{
                selectorCi.next().removeClass('state-error').addClass('state-init');
            }

            //判断次级菜单
            if (x.value == "") {
                $(x).next().removeClass('state-init').addClass('state-error');
            }else{
                $(x).next().removeClass('state-error').addClass('state-init');
            }
            return;
        }

        //batteryType
        if(x.name == "batteryType"){
            if($(x).val()){
                $(x).next().removeClass('state-error').addClass('state-init');
            }else{
                $(x).next().removeClass('state-init').addClass('state-error');
            }
            return;
        }

        //batterySeriesNumber
        if(x.name == "batterySeriesNumber"){
            if($(x).val()){
                $(x).next().removeClass('state-error').addClass('state-init');
            }else{
                $(x).next().removeClass('state-init').addClass('state-error');
            }
            return;
        }

        //factoryName
        if(x.name == "factoryName"){
            if($(x).val()){
                $(x).next().removeClass('state-error').addClass('state-init');
            }else{
                $(x).next().removeClass('state-init').addClass('state-error');
            }
            return;
        }

        //damageType
        if(x.name == "damageType"){
            if($(x).val()){
                $(x).next().removeClass('state-error').addClass('state-init');
            }else{
                $(x).next().removeClass('state-init').addClass('state-error');
            }
            return;
        }

        //result
        if(x.name == "result"){
            if($(x).val()){
                $(x).next().removeClass('state-error').addClass('state-init');
            }else{
                $(x).next().removeClass('state-init').addClass('state-error');
            }
            return;
        }



    }



</script>